<template>
    <div class="app-container">
        <el-input placeholder="输入文章标题" style="width:50%;margin: 5px;" v-model="article.title" size="small"></el-input>
        <div class="upload" style="width:50%;margin: 5px;">
            <el-upload
                class="upload-demo"
                action="string"
                :limit="1"
                :file-list="fileList"
                :http-request="handlePost"
                :on-exceed = "onExceed"
                list-type="picture">
                <el-button size="small" type="primary">点击上传文章封面</el-button>
            </el-upload>
        </div>
        <div style="display:flex">
            <div ref="editor" class="text" ></div>
            <div class="editor-content" v-html="article.content"/>
        </div>
        <div style="margin: 5px;">
            <span>文章类型：</span>
            <el-select v-model="article.categoryId" placeholder="请选择" size="small">
                <el-option v-for="(item,index) in categoryList" :key="index" :label="item.name" :value="item.id"></el-option>
            </el-select>
            <div style="margin-top:20px;">
                <el-button size="small" type="primary" @click="handlePub(1)">发布博客</el-button>
                <el-button size="small" type="primary" @click="handleSave(1)">保存草稿</el-button>
                <el-button size="small" type="info" @click="back()">返回</el-button>
            </div>
        </div>
    </div>
</template>
<script>
import wangeditor from 'wangeditor'
import { queryCategory } from '@/api/category'
import { addArticle,editArticle } from '@/api/article'
import { upload } from '@/api/fileUpload'
import { getToken } from '@/utils/auth'
const defaultSettings = require('@/settings.js')
export default {
    name: "WriteArticle",
    // 设置数据字典
    components:{
        // 'article-add-and-edit':AddAndEdit,  //新增/编辑日志组件
    },
    data() {
        return{
            uploadUrl:defaultSettings.devApiUrl+'article/uploadImage/'+'123456789',
            fileList:[],
            categoryList:[],//文章分类
            article:{
                id:'',
                title:'',
                content:'',
                categoryId:''
            }
        }
    },
    created(){
        this.getData()
        let article = this.$route.query.param
        if(article){
            this.article = article
            this.fileList.push({url:this.article.image})
            // alert(JSON.stringify(this.article))
        }else{
            this.addArticle()
        }
    },
    mounted() {
        this.initWangeditor()
    },
    methods:{
        getData(){
            //调用获取文章分类接口
            this.apiQueryCategory()
        },
        onExceed(){
            this.$message.error("上传文件突破限制!")
        },
        handlePost(fileItem) {
            let param =new FormData();
            param.append('file',fileItem.file)
            let url = "/api/article/uploadImage/"+this.article.id
            upload(url,param).then(res =>{
                if(res.data.code === 200){
                    this.$message.success(res.data.message)
                    this.visible=false
                    this.reload()
                }
            })
        },
        handleSave(type){
            let params = {
                id:this.article.id,
                title:this.article.title,
                content:this.article.content,
                categoryId:this.article.categoryId,
                state : 0
            }
            this.apiEditArticle(params,type)
        },
        back(){
            this.$router.push({path:'/blog/article'})
        },
        initWangeditor(){
            let editor = new wangeditor(this.$refs.editor)
             //开启debug模式
            editor.customConfig.debug = true;
            // 关闭粘贴内容中的样式
            editor.customConfig.pasteFilterStyle = false
            // 忽略粘贴内容中的图片
            editor.customConfig.pasteIgnoreImg = false
            // 使用 base64 保存图片
            //editor.customConfig.uploadImgShowBase64 = true
        
            editor.customConfig.uploadImgParams = {
                // 如果版本 <=v3.1.0 ，属性值会自动进行 encode ，此处无需 encode
                // 如果版本 >=v3.1.1 ，属性值不会自动 encode ，如有需要自己手动 encode
                id: this.article.id
            }
            editor.customConfig.uploadImgHeaders = {
                'Authorization' : "Bearer " + getToken()
            }
            editor.customConfig.uploadFileName = "file";
            editor.customConfig.uploadImgServer = '/api/article/uploadContentImg';
        
            //自定义上传图片事件
            editor.customConfig.uploadImgHooks = {
                before: function (xhr, editor, files) {
        
                },
                success: function (xhr, editor, result) {
                    console.log("上传成功");
                },
                fail: function (xhr, editor, result) {
                    console.log("上传失败,原因是" + result);
                },
                error: function (xhr, editor) {
                    console.log("上传出错");
                },
                timeout: function (xhr, editor) {
                    console.log("上传超时");
                },
                customInsert: function (insertImg, result, editor) {
                    // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
                    // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果
        
                    // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
                    var url = result.url;
                    insertImg(url)
        
                    // result 必须是一个 JSON 格式字符串！！！否则报错
                }
        
            };
            // 自定义文件名，不可修改，修改后会上传失败
            editor.customConfig.onchange = (html) => {
                this.article.content = html
            }
            editor.create()
            // 初始化数据
            editor.txt.html(this.article.content)
        },
        addArticle(){
            let params = {
                state : 3
            }
            this.apiAddArticle(params)
        },
        handlePub(){
            if( !this.article.title ){
                this.$message.warning("请输入文章标题")
            }else if(this.fileList.length === 0){
                this.$message.warning("请上传文章封面")
            }else if( !this.article.content || this.article.content.length <100){
                this.$message.warning("正文内容不能小于100字")
            }else if( !this.article.categoryId ){
                this.$message.warning("请选择文章类型")
            }else{
                let params = {
                    id:this.article.id,
                    title:this.article.title,
                    content:this.article.content,
                    categoryId:this.article.categoryId,
                    state : 1
                }
                this.apiEditArticle(params,1)
            }
        },
        //==========>请求api接口<==========//
        apiAddArticle(article){
            addArticle(article).then(res =>{
                if(res.code === 200){
                    this.article.id = res.data
                }
            },error =>{
            })
        },
        apiEditArticle(article,type){
            editArticle(article).then(res =>{
                if(res.code === 200){
                    this.$message.success("保存成功")
                    type === 1 && this.$router.push({path:'/blog/article'})
                }
            },error =>{
            })
        },
        apiQueryCategory(){
            let params = {
                keyWord : this.keyWord,
                pageNum:1,
                pageSize:10
            }
            queryCategory(params).then(res=>{
                if(res.code ===200){
                    this.categoryList    = res.data.list
                }
            })
        }
        //==========>请求api接口<==========//
    }
}
</script>

<style scoped>
.editor-content{
    width: 50%;
    height: 600px;
    overflow:scroll;
    margin-top: 34px;
}
.text {
    width: 50.5%;
    text-align:left;
    margin: 5px
}
.text >>> .w-e-text-container{
    height: 600px !important;
}
</style>